<template>
  <div class="app-container calendar-list-container">
    <el-row>
      <el-col :span="8">
        <div class="grid-content bg-purple" style="margin-right: 10px;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <div style="display: inline-block;width: 30%">区域架构</div>
              <div style="width: 68%; text-align: right;display: inline-block;"><el-button size="small" type="primary"  icon="plus" @click="append">新增区域</el-button></div>
            </div>
            <div>
              <el-input placeholder="输入关键字进行过滤" v-model="filterText">
              </el-input>
              <el-tree class="filter-tree" node-key="id" :data="mainTreeData" :props="defaultProps" default-expand-all
                       :expand-on-click-node="false"
                       :filter-node-method="filterNode" ref="mainTree" highlight-current
                       :render-content="renderContent" @node-click="getTreeNodeData">
              </el-tree>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="16" style="height:100%">
        <div class="grid-content bg-purple-light">
          <el-card class="box-card" >
            <div slot="header" class="clearfix">
              <span>{{mainTreeForm.parentId==='-1'?'区域编辑':'社区编辑'}}</span>
            </div>
            <div>
              <!-- 表单提交 -->
              <el-form :model="mainTreeForm" status-icon :rules="mainTreeFormRules" ref="mainTreeForm"
                       label-width="100px" class="demo-ruleForm">
                <el-form-item :label="mainTreeForm.parentId==='-1'?'区域编辑':'社区编辑'" prop="regionName">
                  <el-input v-model="mainTreeForm.regionName" placeholder="请输入区域名称" :disabled="formEdit"></el-input>
                </el-form-item>

                <el-form-item :label="mainTreeForm.parentId==='-1'?'区域编码编辑':'社区编码编辑'" prop="gatherId">
                  <el-input  v-model="mainTreeForm.gatherId" placeholder="请输入区域编码名称" :disabled="formEdit"></el-input>
                </el-form-item>

                <el-form-item v-if="mainTreeForm.id&&mainTreeForm.parentId!=='-1'">
                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <span>采集员列表</span>
                    <el-button type="success"  @click="handlerUser">
                      {{dialogUserName}}</el-button>
                  </div>
                  <el-table :data="groupUsers">
                    <el-table-column prop="username" label="用户名" >
                    </el-table-column>
                    <el-table-column prop="name" label="姓名">
                    </el-table-column>
                    <el-table-column prop="sex" label="性别">
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="60" fixed="right">
                      <template slot-scope="scope">
                        <el-button    size="mini" type="danger" @click="handleRemove(scope.row)">移除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
                </el-form-item>


                <el-form-item>
                  <el-button type="primary" @click="handlerMainTreeForm('mainTreeForm')" v-if="areaManager_btn_edit"
                             :disabled="formEdit">提交
                  </el-button>
                  <el-button @click="editTreeFormFlag = false" :disabled="formEdit">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-dialog :title="dialogUserName" :visible.sync="dialogUserVisible">
        <group-user :groupId="mainTreeForm.id" :mItems="mItems" @closeUserDialog="closeUserDialog" ref="groupUser"></group-user>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
  import {
    fetchTree,
    addRegionObj,
    putRegionObj,
    getRegionObj,
    delRegionObj,
    getGather,
    findUser
  } from '@/api/admin/region/index';
  import { mapGetters } from 'vuex';

  export default {
    components: {
      'group-user': () => import('./components/groupUser')
    },
    watch: {
      '$route'() {
        this.initmainTreeData()
      },
      filterText(val) {
        this.$refs.mainTree.filter(val);
      }
    },
    methods: {
      closeUserDialog() {
        this.dialogUserVisible = false;
        this.getGatherList(this.regionId)
      },
      handlerUser() {
        this.dialogUserVisible = true;
        this.getUser()
      },
      getUser() {
        findUser(this.id).then(response => {
          this.mItems = response.data
        });
      },
      getTreeNodeData(data) {
        this.formEdit = false
        this.editTreeFormFlag = true;
        getRegionObj(data.id).then(response => {
          this.mainTreeForm = response.data;
          this.id = this.mainTreeForm.id
        });
        this.groupUsers = []
        if (data.parentId !== '-1') {
          // 获取所有采集员
          this.regionId = data.id
          this.getGatherList(this.regionId);
        }
        this.$refs.mainTree.setCurrentKey(data.id);
      },
      getGatherList(id) {
        // 获取所有采集员
        getGather(id)
          .then(response => {
            this.groupUsers = response.data
          })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      handlerMainTreeForm(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            // 验证该区域是否存在
            putRegionObj(this.mainTreeForm.id, this.mainTreeForm).then(() => {
              this.editTreeFormFlag = false
              this.initmainTreeData();
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      append(node, data) {
        // let entity = {};
        if (data === undefined) {
          data = {}
          data.id = '-1';
          addRegionObj({ regionName: '新区域', parentId: data.id }).then(() => {
            this.initmainTreeData();
          });
        } else {
          addRegionObj({ regionName: '新社区', parentId: data.id }).then(() => {
            this.initmainTreeData();
          });
        }
        this.$refs.mainTree.setCurrentKey(data.id);
      },
      handleRemove(data) {
        delRegionObj(data.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
        });
        const index = this.groupUsers.indexOf(data);
        this.groupUsers.splice(index, 1);
        // this.getGatherList(data.parentId);
      },
      remove(node, data) {
        if (data.children.length > 0) {
          this.$notify({
            title: '失败',
            message: '删除失败，该区域下有其他子区域！',
            type: 'warning',
            duration: 2000
          });
          return;
        }
        delRegionObj(data.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.id === data.id);
          children.splice(index, 1);
        });
        this.$refs.mainTree.setCurrentKey(data.id);
      },
      edit(node, data) {
        this.formEdit = false
        this.editTreeFormFlag = true;
        getRegionObj(data.id).then(response => {
          this.mainTreeForm = response.data;
        });
        this.$refs.mainTree.setCurrentKey(data.id);
      },
      renderContent(h, { node, data }) {
        return (
          < span
            style = "flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;" >
            < span >
              < span > {node.label
              }<
              /span>
            < /span>
            < span >
              {this.areaManager_btn_edit ?
                <
                  el-button
                  style = "font-size: 12px;"
                  type = "text"
                  on-click = {() =>
                    this.edit(node, data)
                  }
                >
                  <
                    i
                    class
                      = "el-icon-edit" / >
                < /el-button> : <span></span >
              }
              {
                this.areaManager_btn_add && data.parentId === '-1' ?
                  <
                    el-button
                    style = "font-size: 12px;"
                    type = "text"
                    on-click = {() =>
                      this.append(node, data)
                    }
                  >
                    <
                      i
                      class
                        = "el-icon-circle-plus-outline" / >
                  < /el-button>
                  : <
                    span > < /span>
              }
              {
                this.areaManager_btn_del ?
                  <el-button
                    style = "font-size: 12px;"
                    type = "text"
                    on-click = {() =>
                      this.remove(node, data)
                    }
                  ><i class="el-icon-delete" />
                  </el-button>
                  : <span></span>
              }
            <
            /span>
          < /span>
        )
        ;
      },
      initmainTreeData() {
        fetchTree().then(data => {
          this.mainTreeData = data.data;
        });
      }
    },
    created() {
      this.mainTreeForm = {}
      this.initmainTreeData()

      // 加载树
      this.areaManager_btn_edit = true;
      this.areaManager_btn_del = true;
      this.areaManager_btn_add = true;
    },
    computed: {
      ...mapGetters(['elements'])
    },
    data() {
      return {
        mItems: [],
        regionId: '',
        dialogUserName: '关联用户',
        groupUsers: [],
        dialogUserVisible: false,
        formEdit: true,
        areaManager_btn_edit: false,
        areaManager_btn_del: false,
        areaManager_btn_add: false,
        filterText: '',
        editTreeFormFlag: true,
        mainTreeForm: {
          regionName: '',
          gatherId: ''
        },
        id: '',
        mainTreeFormRules: {
          regionName: [
            {
              required: true,
              message: '字段不能为空',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 20,
              message: '长度在 1 到 20 个字符',
              trigger: 'blur'
            }
          ]
        },
        mainTreeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      };
    }
  };
</script>
